<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/5/24
 * Time: 11:39
 */

namespace app\supplier\controller;

use app\admin\model\GoodsCate;
use app\admin\model\GoodsSpec;
use app\company\model\CompanyGoodsRate;
use app\company\model\CompanyGoodsRule;
use app\company\model\CompanyOrderDetail;
use app\company\model\CompanyOrderStorage;
use app\company\model\CompanyGoods;
use app\mini\model\StoreOrderDetail;
use app\service\traits\Crud;
use app\supplier\validate\StoreValidate;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;

class Goods extends Base
{
    private CompanyOrderDetail $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new CompanyOrderDetail();
        $this->validateClass = StoreValidate::class;
        $this->withSearch    = 'goods_id,goods_cate_id';
    }

    /**
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(): Response
    {
        $param = $this->request->param();
        $sql   = $this->model->gs($this->company_id)->where('supplier_id', $this->supplier_id)->field('goods_id');
        $sql   = $sql->withSearch('goods_id', $param)->group('goods_id');
        $count = $sql->count();
        if (Request::param('is_export', 0) != 1) $sql = $sql->page($param['page'], $param['limit']);
        $list  = $sql->select()->each(function ($item) {
            $item->goods = $item->goods()->withTrashed()->field('name,img,unit,shelf_life')->find();
            $arr         = CompanyGoods::where('goods_id', $item->goods_id)->gs($this->company_id)->withTrashed()->field('status,racking_time,sold_out_time,goods_cate_id')->find();
            $item->status   = $arr->status;
            $item->racking  = $arr->racking_time;
            $item->sold_out = $arr->sold_out_time;

            $item->goods->goods_cate_name = getGoodsCateName($arr['goods_cate_id']);
            //库存 暂时不取redis 的 有少许误差,会把待支付的统计进去
//            $item->stock = (int)redis()->zScore(kcGoodsKey() . $this->company_id, $item->goods_id);
            $item->stock = CompanyOrderStorage::where('goods_id', $item->goods_id)->where('company_id', $this->company_id)->sum('quantity'); //库存所有规格之和(产品定义)

            //销量
            $item->sales = StoreOrderDetail::hasWhere('storeOrder', function ($query) {
                $query->whereIn('order_status', [2, 3, 4])->where('company_id', $this->company_id);
            })->where('goods_id', $item->goods_id)->sum('quantity');;
        });
        return $this->success('请求成功', compact('list', 'count'));
    }

    public function detail($goods_id): Response
    {
        $filed = 'goods_id,status,racking_time,sold_out_time,goods_cate_id,company_id,descriptions';
        $info  = CompanyGoods::seekGoods($this->company_id, $goods_id)->withTrashed()->field($filed)->find();
        if (!$info) return $this->error('商品不存在');
        $info->goods_spec          = GoodsSpec::where('goods_id', $goods_id)->field('id,name,value')->select();
        $info->goods_cate_name = GoodsCate::where('id', $info->goods_cate_id)->value('name');
        $info->goods               = $info->goods()->field('id,img,name,unit,no,shelf_life,spec_type')->find();
        $info->goods_rule          = CompanyGoodsRule::seekGoods($this->company_id, $goods_id)->withTrashed()->field('id,goods_rule_id,money')->select()->each(function ($item) {
            $filed            = 'id,spec_name,img,purchasing_price,weight';
            $item->goods_rule = $item->goodsRule()->withTrashed()->field($filed)->find();
            //销量
            $item->sales = (int)redis()->zScore(xsGoodsRuleKey() . $this->company_id, $item->goods_rule_id);
        });
        //费率
        $info->rate = CompanyGoodsRate::where('company_id', $info->company_id)->where('goods_id', $info->goods_id)->find();
        return $this->success('请求成功', compact('info'));
    }

    /**
     * 经销商只允许修改售卖价
     * @param $goods_rule_id
     * @param $money
     * @return Response
     */
    public function edit($goods_rule_id, $money): Response
    {
        if (!$model = CompanyGoodsRule::where('company_id', $this->company_id)->goodsRuleId($goods_rule_id)->find())
            return $this->error('商品规格不存在');
        $model->money = $money;
        $model->save();
        return $this->success('修改成功');
    }


    /**
     * 筛选框
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function search(): Response
    {
        $name = request()->param('name', '');
        $list = $this->model->withJoin([
            'goods' => function ($query) use ($name) {
                $query->where('name', 'like', '%' . $name . '%');
            }])->gs($this->company_id)->supplierId($this->supplier_id)->field('goods_id')->distinct(true)->group('goods_id')->select();
        return $this->success('获取成功', compact('list'));
    }

    /**
     * 筛选框 获取规格
     * @return Response
     */
    public function goodsRule(): Response
    {
        $goods_id = request()->param('goods_id', '');
        $slq  = $this->model->gs($this->company_id)->supplierId($this->supplier_id)->field('goods_rule_id');
        $list = $slq->goodsId($goods_id)->distinct(true)->select()->each(function ($item) {
                $item->spec_name = $item->goodsRule()->value('spec_name');
            });
        return $this->success('获取成功', compact('list'));
    }
}